import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import router from '@/router'

let loadingInstance = null

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 显示全局加载
    loadingInstance = ElLoading.service({
      lock: true,
      text: '请求中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 从 store 获取 token 并添加到请求头
    const userStore = useUserStore()
    const token = userStore.token
    if (token) {
      config.headers['Authorization'] = token
    }
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 关闭加载
    if (loadingInstance) {
      loadingInstance.close()
    }
    
    const { code, data, msg } = response.data
    if (code != 200000) {
      ElMessage.error(msg)
      return Promise.reject(new Error(msg))
    }
    return data
  },
  error => {
    // 关闭加载
    if (loadingInstance) {
      loadingInstance.close()
    }
    
    const { response, status } = error
    if (status === 401) {
      const userStore = useUserStore()
      userStore.logoutAction()
      ElMessage.error("登录过期，请重新登录")
      router.push('/login')
    }
    const { code, msg } = response.data
    ElMessage.error(msg)
    return Promise.reject({
      code,
      msg
    })
  }
)

// 导出 axios 实例
export default ({url, method, data, params, headers}) => {
  return service({
    url,
    method,
    data,  
    params,
    headers
  })
} 